<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var x = 1;
        var y = x;
        x = 3
        var j = ['a', 'b']
        var k = j
        j[0] = 'good'
        let str1 = "李大锤"
        let str2 = "李大锤"
        let obj1 = { 'name': "李大锤" }
        let obj2 = { 'name': "李大锤" }
        let obj3 = obj1
        //比较obj1和obj2的地址，也就是指针
        obj1 == obj2 //false
        obj1 == obj3 //true

        var array = [1, 2, 3]
        var arrayCopy = []
        array.forEach(function (el, index) {
            arrayCopy[index] = el
        })

        var array1 = [[1, 2], 3, ['a', 'b']]
        var array1Copy = []
        // for(var i=0;i<array1.length;i++){
        //     array1Copy[i] = array1[i]
        // }
        // array1Copy[0] = array1[0]

        /*---------------------浅拷贝---------------------*/


        let o1 = { hello: "world" }
        let o2 = { hi: "how" }
        //把o2,合并到o1，会改变o1，然后 o3 = o1
        let o3 = Object.assign(o1, o2)

        let x1 = {}
        let x2 = { name: "jack", age: 20 }
        Object.assign(x1, x2)
        //通过object.assign实现浅拷贝
        function assignDeepCopy(obj) {
            return Object.assign({}, obj)
        }
/*---------------------深拷贝---------------------*/

        //把array1对象转换成一个字符串
        var array1CopyStr = JSON.stringify(array1)

        console.log(array1CopyStr)
        console.log(typeof array1CopyStr)
        //把字符串解析为一个对象
        var array1Copy1 = JSON.parse(array1CopyStr)

        //通过json模块实现深拷贝
        function jsonDeepCopy(obj) {
            //把对象JSON化生成要给字符串
            let objStr = JSON.stringify(obj)
            //把这个字符串解析为一个对象
            return JSON.parse(objStr)
        }

        a1 = { x: 1, y: 2 }
        a2 = jsonDeepCopy(a1)

        let lucy = { name: 'lucy', age: 24 }
        let lucyCopy = assignDeepCopy(lucy)
        let s = {}
        deepCopy(school, s)
        //通过递归的方式实现深拷贝
        function dp(obj, copy) {
            for (key in obj) {
                if (typeof obj[key] == "object") {
                    copy[key] = Array.isArray(obj[key]) ? [] : {}
                    dp(obj[key], copy[key])
                } else {
                    copy[key] = obj[key]
                }
            }
        }
        let p = {
            name: 'tony老师',
            age: 28,
            fav: ['洗', '剪', '吹']
        }
        let p1 = {}
        dp(p,p1)


    </script>
</body>

</html>